package com.zycfc.zsf.boot.serializer.hessian;

import com.zycfc.zsf.boot.serializer.*;
import java.io.*;
import com.caucho.hessian.io.*;

public class HessianSerializer implements ISerializer
{
    private static final SerializerFactory SERIALIZER_FACTORY;
    
    public void addSerializerFactory(final AbstractSerializerFactory factory) {
        HessianSerializer.SERIALIZER_FACTORY.addFactory(factory);
    }
    
    @Override
    public byte[] serialize(final Object obj) throws Exception {
        if (obj == null) {
            return null;
        }
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final AbstractHessianOutput output = (AbstractHessianOutput)new Hessian2Output((OutputStream)outputStream);
        output.setSerializerFactory(HessianSerializer.SERIALIZER_FACTORY);
        output.writeObject(obj);
        output.flush();
        final byte[] val = outputStream.toByteArray();
        output.close();
        return val;
    }
    
    @Override
    public Object deserialize(final byte[] bytes) throws Exception {
        if (null == bytes || bytes.length == 0) {
            return null;
        }
        final ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        final AbstractHessianInput input = (AbstractHessianInput)new Hessian2Input((InputStream)inputStream);
        input.setSerializerFactory(HessianSerializer.SERIALIZER_FACTORY);
        final Object obj = input.readObject();
        input.close();
        return obj;
    }
    
    static {
        (SERIALIZER_FACTORY = new SerializerFactory()).addFactory((AbstractSerializerFactory)new HessionBigDecimalSerializerFactory());
        HessianSerializer.SERIALIZER_FACTORY.addFactory((AbstractSerializerFactory)new HessionSoftReferenceSerializerFactory());
    }
}
